package wnhz.com.business.shareshop.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.groupshop.adapter.QuanZiImageAdapter;
import wnhz.com.business.groupshop.ui.DetailsActivity;
import wnhz.com.business.shareshop.bean.MyCollectionShareBean;
import wnhz.com.business.shareshop.bean.PingJiaDetailsBean;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.StatusBarUtil;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.ExpandTextView;
import wnhz.com.business.view.MyRecyclerView;
import wnhz.com.business.view.NoScrollGridView;


/**
 * 共享商城评论详情
 */
public class AllCommentActivitySS extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.v_statusbar)
    View vStatusbar;
    @BindView(R.id.iv_actionbar_left)
    ImageView ivActionbarLeft;
    @BindView(R.id.tv_actionbar_left)
    TextView tvActionbarLeft;
    @BindView(R.id.lay_actionbar_left)
    RelativeLayout layActionbarLeft;
    @BindView(R.id.tv_actionbar_title)
    TextView tvActionbarTitle;
    @BindView(R.id.iv_actionbar_right)
    ImageView ivActionbarRight;
    @BindView(R.id.tv_actionbar_right)
    TextView tvActionbarRight;
    @BindView(R.id.lay_actionbar_right)
    RelativeLayout layActionbarRight;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_sku)
    TextView tvSku;
    @BindView(R.id.tv_userComment)
    ExpandTextView tvUserComment;
    @BindView(R.id.gridview)
    NoScrollGridView gridview;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.rl_body)
    RelativeLayout rlBody;

    @BindView(R.id.rl_anwser)
    MyRecyclerView rlAnwser;
    @BindView(R.id.ll_pinglun)
    LinearLayout llPinglun;
    @BindView(R.id.ll_dianzan)
    LinearLayout llDianzan;
    @BindView(R.id.tv_dianzan)
    TextView tv_dianzan;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<String> datalist = new ArrayList<>();
    private List<String> imglist = new ArrayList<>();
    private PopupWindow caozuopop;
    private TextView tv_pop1, tv_pop2, tv_pop3, tv_pop4, tv_pop_make,line1,line2,line3;
    private RelativeLayout rl_head;
    private String from = "",is_like="0",copy_content="";
    private String type="1";//是评价还是回复
    private String commentId,response_name,responseId,user_id= Prefer.getInstance().getUser_id();//评价id
    PingJiaDetailsBean.InfoBean.GoodsCommentBean content ;
    List<PingJiaDetailsBean.InfoBean.ReportListBean> response = new ArrayList<>();
    List<PingJiaDetailsBean.InfoBean.ReportListBean.ItemBean> response_item = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;
    private int rpage=0,page=0;
    private boolean is_me;//是否是我自己
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_comment_ss);
        ButterKnife.bind(this);
        commentId = getIntent().getStringExtra("commentId");
        is_like = getIntent().getStringExtra("is_like");
        getData();
//        //状态栏设置
//        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.transparent), 0);
//        StatusBarUtil.setDarkMode(this, true);
//        StatusBarUtil.immersive(this, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //透明导航栏
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //改变状态栏颜色
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            //获取到状态栏的高度
            int statusHeight = getStatusBarHeight();
            //动态的设置隐藏布局的高度
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) vStatusbar.getLayoutParams();
            params.height = statusHeight;
            vStatusbar.setLayoutParams(params);
        }
    }
    private void getData() {
        Map<String,Object> map = new HashMap<>();
        map.put("commentId",commentId);//评价ID
        map.put("page", page+"");//页码
        map.put("rpage", rpage+"");//子回复页码
        map.put("token", MyApplication.getToken());
        map.put("goods_type", "4");//1.拼团 2.返利  3.免费  4：共享商城
        XUtil.Post(Url.GOODS_EVALUATEDETAILLIST_DETAILS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        Gson gson = new Gson();
                        PingJiaDetailsBean item = gson.fromJson(result, PingJiaDetailsBean.class);
                        content = item.getInfo().getGoods_comment();
                        setContent();
//                        response = item.getInfo().getReport_list();
//                        setdata();
                        if (page == 0){
                            if (null != response){
                                response.clear();
                            }
                            response = item.getInfo().getReport_list();
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mBaseAdapter.notifyDataSetChanged();

                        }
                        setdata();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 0){
                            mRefreshLayout.setVisibility(View.GONE);
//                            empty_layout.setVisibility(View.VISIBLE);
                            MyToast(jsonObject.optString("info"));
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
//                            empty_layout.setVisibility(View.GONE);
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    private void setContent() {//设置上方评论的数据
        Glide.with(AllCommentActivitySS.this).load(content.getHeadimg()).error(R.drawable.img_default_portrait).into(ivHead);
        Glide.with(AllCommentActivitySS.this).load(content.getGoods_pic()).into(ivImg);
        tvName.setText(content.getNickname());
        tvTime.setText(content.getPosttime());
        tvSku.setText(content.getGoods_name());
        tvUserComment.setText(content.getContent());
        QuanZiImageAdapter ziImageAdapter = new QuanZiImageAdapter(AllCommentActivitySS.this, content.getPic());
        gridview.setAdapter(ziImageAdapter);
        tvLocation.setText(content.getViewcount()+"人浏览      "+content.getLikecount()+"个人觉得很赞");

        if(is_like.equals("0")){
            tv_dianzan.setText("点赞");
        }else{
            tv_dianzan.setText("已赞");
        }
    }
    private void setdata() {
        rlAnwser.setLayoutManager(new LinearLayoutManager(AllCommentActivitySS.this,LinearLayoutManager.VERTICAL,false));
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setRefreshHeader(null);
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        mBaseAdapter = new BaseRVAdapter(AllCommentActivitySS.this,response) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_conment_list;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                Glide.with(AllCommentActivitySS.this).load(response.get(position).getHeadimg()).error(R.drawable.img_default_portrait).into(holder.getImageView(R.id.ic_icon));
                if(TextUtils.isEmpty(response.get(position).getNickname())){
                    response_name = "未知用户";
                }else {
                    response_name = response.get(position).getNickname();
                }
                holder.getTextView(R.id.tv_minename).setText(response_name);
                holder.getTextView(R.id.tv_timess).setText(response.get(position).getCreatetime());
                holder.getTextView(R.id.tv_reson).setText(response.get(position).getContent());
                response_item = response.get(position).getItem();
                holder.getImageView(R.id.iv_bianzie).setOnClickListener(new View.OnClickListener() {//点击编辑按钮
                    @Override
                    public void onClick(View v) {
                        if(response.get(position).getUser_id().equals(user_id)){
                            is_me = true;
                        }else{
                            is_me = false;
                        }
                        responseId = response.get(position).getItem_id();//回复的id
                        copy_content = response.get(position).getContent();
                        type = "2";//回复
                        from = "1";
                        huifupinglun();
                    }
                });
                MyRecyclerView myRecyclerView = (MyRecyclerView) holder.getView(R.id.rl_anwser);
                myRecyclerView.setLayoutManager(new LinearLayoutManager(AllCommentActivitySS.this,LinearLayoutManager.VERTICAL,false));
                BaseRVAdapter myAdapter = new BaseRVAdapter(AllCommentActivitySS.this, response_item) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_pinglun;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position) {
                        holder.getTextView(R.id.tv_huifuren).setText(response_item.get(position).getNickname());
                        holder.getTextView(R.id.tv_beihuifuren).setText(response_name);
                        holder.getTextView(R.id.tv_datatime).setText(response_item.get(position).getAddtime());
                        holder.getTextView(R.id.tv_huifucontext).setText(response_item.get(position).getContent());
                    }
                };
                myRecyclerView.setAdapter(myAdapter);
            }
        };
        rlAnwser.setAdapter(mBaseAdapter);
}
private void response(){//跳出评价，回复别人的窗口
    String hint = "我也说一句...";
    showInputComment(AllCommentActivitySS.this, hint, new DetailsActivity.CommentDialogListener() {
        @Override
        public void onClickPublish(final Dialog dialog, EditText input, final TextView btn) {
            final String content = input.getText().toString();
            if (content.toString().equals("")) {
                Toast.makeText(AllCommentActivitySS.this, "评论不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            Map<String,Object> map = new HashMap<>();
            if(type.equals("1")){//评论
                map.put("commentId",commentId);//评价ID
            }else{//回复
                map.put("commentId",responseId);//评价ID
            }
            map.put("type",type);//评价1,回复2
            map.put("content", content);
            map.put("token", MyApplication.getToken());
            XUtil.Post(Url.GOODS_COMMON_REPLY, map, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String re = jsonObject.getString("re");
                        if ("1".equals(re)) {
                            if(TextUtils.isEmpty(jsonObject.getString("info"))){
                                MyToast("评论成功");
                            }else{
                                MyToast(jsonObject.getString("info"));
                            }
                        }else  if ("-1".equals(jsonObject.getString("result"))){
                            MyApplication.getInstance().gotoLoginActivity();
                        }else{
                            MyToast(jsonObject.getString("info"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onFinished() {
                    super.onFinished();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                }
            });
            dialog.dismiss();
        }

        @Override
        public void onShow(int[] inputViewCoordinatesInScreen) {

        }

        @Override
        public void onDismiss() {

        }
    });
}
    private void huifupinglun() {

                View contentView = LayoutInflater.from(AllCommentActivitySS.this).inflate(R.layout.layout_reply_pop, null);
                caozuopop = new PopupWindow(contentView);
                caozuopop.setOutsideTouchable(true);
                caozuopop.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                caozuopop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                if (Build.VERSION.SDK_INT < 24) {
                    caozuopop.showAsDropDown(vStatusbar);
                } else {
                    // 获取控件的位置，安卓系统>7.0
                    int[] location = new int[2];
                    vStatusbar.getLocationOnScreen(location);
                    caozuopop.showAtLocation(vStatusbar, Gravity.NO_GRAVITY, 0, location[1] + vStatusbar.getHeight());
                }


                tv_pop1 = (TextView) contentView.findViewById(R.id.tv_pop_1);
                tv_pop2 = (TextView) contentView.findViewById(R.id.tv_pop_2);
                tv_pop3 = (TextView) contentView.findViewById(R.id.tv_pop_3);
                tv_pop4 = (TextView) contentView.findViewById(R.id.tv_pop_4);
                line1 = (TextView) contentView.findViewById(R.id.line1);
                line2 = (TextView) contentView.findViewById(R.id.line2);
                line3 = (TextView) contentView.findViewById(R.id.line3);
                rl_head = (RelativeLayout) contentView.findViewById(R.id.rl_head);
                tv_pop_make = (TextView) contentView.findViewById(R.id.tv_pop_make);


                if ("1".equals(from)) {
                    if(is_me){//有删除按钮
                        tv_pop1.setVisibility(View.VISIBLE);
                        tv_pop2.setVisibility(View.VISIBLE);
                        tv_pop3.setVisibility(View.VISIBLE);
                        line1.setVisibility(View.VISIBLE);
                        line2.setVisibility(View.VISIBLE);
                        line3.setVisibility(View.VISIBLE);
                    }else{
                        tv_pop1.setVisibility(View.VISIBLE);
                        tv_pop2.setVisibility(View.VISIBLE);
                        tv_pop3.setVisibility(View.GONE);
                        line1.setVisibility(View.VISIBLE);
                        line2.setVisibility(View.VISIBLE);
                        line3.setVisibility(View.GONE);
                    }
                } else {
                    tv_pop1.setVisibility(View.GONE);
                    tv_pop2.setVisibility(View.GONE);
                    tv_pop3.setVisibility(View.GONE);
                    line1.setVisibility(View.GONE);
                    line2.setVisibility(View.GONE);
                    line3.setVisibility(View.GONE);
                }


                //回复
                tv_pop1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        type = "2";//回复
                        response();
                        caozuopop.dismiss();

                    }
                });
                //复制
                tv_pop2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                        cmb.setText(copy_content);
                        MyToast("内容复制成功");
                        caozuopop.dismiss();

                    }
                });
                //删除
                tv_pop3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deletePingjia();
                        caozuopop.dismiss();

                    }
                });
                //举报
                tv_pop4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(AllCommentActivitySS.this, JUbaoActivityS.class);
                        if(type.equals("1")){//评论
                            intent.putExtra("commentId",commentId);
                        }else{//回复
                            intent.putExtra("commentId",responseId);
                        }
                        intent.putExtra("type",type);
                        startActivity(intent);
                        caozuopop.dismiss();
                    }
                });


                //关闭
                rl_head.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        caozuopop.dismiss();
                    }
                });

                //关闭
                tv_pop_make.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        caozuopop.dismiss();
                    }
                });


            }
    @OnClick({R.id.lay_actionbar_left, R.id.lay_actionbar_right, R.id.ll_pinglun, R.id.ll_dianzan})
    public void onViewClicked(View view) {
                switch (view.getId()) {
                    case R.id.lay_actionbar_left://关闭
                        finish();
                        break;
                    case R.id.lay_actionbar_right://右上角举报
                        type = "1";//评论举报
                        from = "2";
                        huifupinglun();
                        break;
                    case R.id.ll_pinglun://评论
                        from = "1";
                        response();
                        break;
                    case R.id.ll_dianzan://点赞
                        UpDianZanData();
                        break;
                }
            }
    private void deletePingjia() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        if(type.equals("1")){//评论
            map.put("commentId",commentId);//评价ID
        }else{//回复
            map.put("commentId",responseId);//评价ID
        }
        XUtil.Post(Url.PINGJIA_DELETE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    String info = jsonObject.optString("info");
                    if ("1".equals(re)) {
                        getData();
                        MyToast("删除成功");
                    }else{
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }
    private void UpDianZanData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("commentId", commentId);
        XUtil.Post(Url.PINGJIA_DIANZAN, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    String info = jsonObject.optString("info");
                    if ("1".equals(re)) {
                        if(is_like.equals("0")){
                            tv_dianzan.setText("已赞");
                            is_like="1";
                        }else{
                            tv_dianzan.setText("点赞");
                            is_like="0";
                        }
                         MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }
    /**
     * 弹出评论对话框
     */
    private static Dialog showInputComment(Activity activity, CharSequence hint, final DetailsActivity.CommentDialogListener listener) {
        final Dialog dialog = new Dialog(activity, android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.view_input_comment);
        dialog.findViewById(R.id.input_comment_dialog_container).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (listener != null) {
                    listener.onDismiss();
                }
            }
        });
        final EditText input = (EditText) dialog.findViewById(R.id.input_comment);
        input.setHint(hint);
        final TextView btn = (TextView) dialog.findViewById(R.id.btn_publish_comment);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClickPublish(dialog, input, btn);
                }
            }
        });
        dialog.setCancelable(true);
        dialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    int[] coord = new int[2];
                    dialog.findViewById(R.id.input_comment_container).getLocationOnScreen(coord);
                    // 传入 输入框距离屏幕顶部（不包括状态栏）的长度
                    listener.onShow(coord);
                }
            }
        }, 300);
        return dialog;
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = page + 1;
                getData();
            }
        },2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 0;
                getData();
            }
        },2000);
    }

    public interface CommentDialogListener {
        void onClickPublish(Dialog dialog, EditText input, TextView btn);

        void onShow(int[] inputViewCoordinatesOnScreen);

        void onDismiss();
    }
    }

